/*
send message GUI functions
*/

function placeExtraFunctionBoxOnPage()	{
	var breadCrumbsDiv = $X(".//*[@id='breadcrumbs']");
	var parentNode = breadCrumbsDiv.parentNode;
	
	var embassyMenu = generateDivBoxLikeEmbassyMenu();	
	parentNode.insertBefore( embassyMenu , breadCrumbsDiv);
	
	replaceBackLinkStartValue();
	
	noticeDiv = $X(".//div[@id='mainview']/div[@id='notice']");
	var messageForm = $X("./form", noticeDiv );
	var originalButton = $X("./div[@class='centerButton']/input", messageForm );
	
	/*
	var originalMessageTextArea = $X("./span/textarea[@id='text']", messageForm );	
	addEvent( originalMessageTextArea, 'blur', function(event){saveMessagePart(event);}, false );
	
	var savedMessagePart = GM_getValue( (gameServer.replace(/\./g, '_') + '_' + MESSAGE_PART_VARIABLE_SUFFIX) );	
	if ( savedMessagePart != null && savedMessagePart != 'undefined')	{
		var loadMessagePartButton = document.createElement('input');
		loadMessagePartButton.type = 'button';
		loadMessagePartButton.className = 'button';
		loadMessagePartButton.title = getButtonTextInLang( 'LOAD_DRAFT_BUTTON_TEXT' );
		loadMessagePartButton.value = getButtonTextInLang( 'LOAD_DRAFT_BUTTON_TEXT' );
		addEvent( loadMessagePartButton	, 'click', function(){loadMessagePart();}, false );
		originalButton.parentNode.appendChild( loadMessagePartButton );
	}
	*/
	if ( url.indexOf('view=sendIKMessage') > 0 && url.indexOf('allyId=') < 0 )	{	
//		parentNode.insertBefore( createAddresBookContainer(), breadCrumbsDiv);
		overrideDefaultSenderButton(originalButton.parentNode);
	}		
}
/*
function saveMessagePart(event)	{
	var trg = event.currentTarget;
	GM_setValue( (gameServer.replace(/\./g, '_') + '_' + MESSAGE_PART_VARIABLE_SUFFIX), escape(trg.value) );
}

function loadMessagePart()	{
	var originalMessageTextArea = $X(".//*[@id='mainview']/div/form/span/textarea[@id='text']");
	var savedMessagePart = unescape(GM_getValue(gameServer.replace(/\./g, '_') + '_' + MESSAGE_PART_VARIABLE_SUFFIX ));
	if ( savedMessagePart != null && savedMessagePart != 'undefined')	{
		originalMessageTextArea.value =savedMessagePart;
	}
}
*/
function overrideDefaultSenderButton(centerDiv)	{
	/*
	var myButton = document.createElement('input');
	myButton.type = 'button';
	myButton.className = 'button';
	myButton.title = getButtonTextInLang( 'SEND_MESSAGE_BUTTON_TEXT' );
	myButton.value = getButtonTextInLang( 'SEND_MESSAGE_BUTTON_TEXT' );
	addEvent( myButton	, 'click', function(){sendMyMessage()}, true );
	
	centerDiv.removeChild( originalButton );
	centerDiv.appendChild( myButton );	
	*/
	var allyDetails = GM_getValue( 'PLAYER_ALLY_DETAILS' );
	var allyId = parseInt(allyDetails.split('=')[0]);
	if ( allyId != 0 )	{
		var sendAllyMessageButton = document.createElement('input');
		sendAllyMessageButton.type = 'button';
		sendAllyMessageButton.className = 'button';
		sendAllyMessageButton.title = getButtonTextInLang( 'SEND_ALLY_MESSAGE_BUTTON_TEXT' );
		sendAllyMessageButton.value = getButtonTextInLang( 'SEND_ALLY_MESSAGE_BUTTON_TEXT' );
		addEvent( sendAllyMessageButton	, 'click', function(){sendAllyMessage();}, true );	
		centerDiv.appendChild( sendAllyMessageButton );
	}
	
	return;
}

function generateDivBoxLikeEmbassyMenu()	{
	var menuDiv = document.createElement('div');
	menuDiv.id = 'boxLikeEmbassyMenu';	
	menuDiv.className = 'dynamic';
	menuDiv.style.display = 'block';	
	// Box ready
	
	var headerObj = document.createElement('h3');
	headerObj.className = 'header';
	headerObj.innerHTML = getOtherTextInLang('MESSAGE_BOX_HEADER') + ' ' + getLanguageForDisplay(); 
	// Header ready	
	
	var contentDiv = document.createElement('div');
	contentDiv.className = 'content';
	contentDiv.style.display = 'block';	
	contentDiv.style.cursor = 'pointer';

	menuDiv.appendChild( headerObj );
	menuDiv.appendChild( createList(contentDiv, null) );		
	
//	menuDiv.appendChild( createSetupButtonTable() );
	
	var footerDiv = document.createElement('div');
	footerDiv.className = 'footer';
	menuDiv.appendChild( footerDiv );
	
	return menuDiv;
}

/*

Functions to create the list with root node and hider element..

*/

function createList( res, resTag )	{
	
	if ( res == null && resTag == null )	{
		return null;
	}
		
	if ( res == null ) 	{
		res = document.createElement(resTag);
	}
	myList = createListRoot( 'myListRoot', 'links', null );	
	var popUpDivForCustomMessageSubject = null;
	var j = 0;
	var myListItem = null;
	for ( j = 0; j < messageTypeKeyWords.length; j++ )	{
		myListItem = createListElement( messageTypeKeyWords[j], null, null , getMenuItemsInLang(messageTypeKeyWords[j]), defaultOnClickEventRequiredForMessageTypeElement[j] );				
		if ( isMessageForTradeGood( j ) ) {
			var popUpDiv = createPopUpDivForTradeMessages( j );		
			var popUpDivId = popUpDiv.id ;
			addEvent( myListItem, 'mouseover', function(objId){showHideObject(this.getElementsByTagName('div')[0].id);}, true );
			addEvent( myListItem, 'mouseout', function(objId){showHideObject(this.getElementsByTagName('div')[0].id);}, true );
			myListItem.appendChild( popUpDiv );				
		}
		else if ( 'CUSTOM' == messageTypeKeyWords[j] )	{
			popUpDivForCustomMessageSubject = createPopUpDivForCustomMessageSubject( j );	
			addEvent( myListItem, 'click', function(objId){showHideObject(popUpDivForCustomMessageSubject.id);}, true );			
		}
		myList.appendChild( myListItem );
	}	
	
	var userDefinedKeyword = null;
	for ( userDefinedKeyword in userDefinedMenuOptions )	{
		myListItem = createListElement( userDefinedKeyword + '_ID', null, null, userDefinedMenuOptions[userDefinedKeyword], false );
		myListItem.title = userDefinedKeyword;
		addEvent( myListItem, 'click', function(){searchAndReplacePreviousSubject( this.id.replace('_ID_extraOptionsListItem', ''), null );}, true );		
		myList.appendChild( myListItem );
	}
	
	
	if ( userSettingValues['ADDITIONAL_MESSAGE_EDITOR_OPTIONS'] )	{
		myListItem = createListElement( 'CLEARMARKER_ID', null, null, getAdditonalMessageEditorListItemsInLang('CLEARMARKER_TEXT'), false );
		addEvent( myListItem, 'click', function(){document.getElementById('text').value = deleteMarkerFromMessage( null, document.getElementById('text').value );}, true );
		myList.appendChild( myListItem );	
		
		myListItem = createListElement( 'CLEARMESSAGE_ID', null, null, getAdditonalMessageEditorListItemsInLang('CLEARMESSAGE_TEXT'), false );
		addEvent( myListItem, 'click', function(){ if ( window.confirm( getOtherTextInLang('CONFIRM_DELETE_MESSAGE_TEXT') ) ) { document.getElementById('text').value = ''; } }, true );
		myList.appendChild( myListItem );
	}	
	
	myListBox = createDivForExtraMessageTypes();
	myListBox.appendChild( myList );	

	myListBox.appendChild( popUpDivForCustomMessageSubject );
	
	myListController = createDivForExtraMessageTypesController();
	addEvent( myListController, 'click', function(){openCloseObject( 'extraMenuBox' ); }, true );		
	res.appendChild( myListController );			
	res.appendChild( myListBox );			
	
	return res;
}


function createListRoot(listId, listClass, listStyle)	{	
	var res = document.createElement('ul');
	res.id = listId;	
	if ( listClass != null ) 	{
		res.className = listClass;
	}
	res.style.display = 'block';
	return res;
}

function createListElement( elementId, emelentClass, elementStyle, elementText, addDefaultOnclickEvent )	{
	var res = document.createElement('li');
	res.id = elementId + '_extraOptionsListItem' ;
	if ( emelentClass != null ) {
		res.className = emelentClass;
	}
	
	res.innerHTML = elementText;	
	if ( addDefaultOnclickEvent )	{
		addEvent( res, 'click', function(){searchAndReplacePreviousSubject( getKeywordsInLang(elementId), null );}, true );			
	}
		
	return res
}

function createDivForExtraMessageTypesController()	{
		var menuObject = document.createElement("div");
		menuObject.id = 'extraMenuBoxContainer';
		menuObject.setAttribute('align','left');
		menuObject.style.margin = '0px auto';
		menuObject.style.visibility = 'visible';
		menuObject.style.display = 'block';
		menuObject.innerHTML = getOtherTextInLang('MY_LIST_ROOT_TEXT');
		return menuObject;				
}

function createDivForExtraMessageTypes()	{
	var menuObject = document.createElement("div");
	menuObject.id = 'extraMenuBox';
	menuObject.setAttribute('align','left');
	menuObject.style.margin = '0px auto';
	menuObject.style.visibility = 'visible';
	menuObject.style.display = userSettingValues['STARTING_DISPLAY_STATE_FOR_SPECIAL_MESSAGES_LIST'];
	return menuObject;				
}

function createPopUpDivForCustomMessageSubject(indexOfMessageType)	{	
	
	var popUp = document.createElement('div');
	popUp.id = messageTypeKeyWords[indexOfMessageType] + '_popUpDiv';
	
	popUp.className = 'dynamic';
	popUp.style.position = 'absolute'; 
	popUp.style.left = '-10px';
	popUp.style.bottom = '10px';
	popUp.style.zIndex = '3';
	popUp.style.visibility = 'hidden'; 
	
	var popUpHeader = document.createElement('h3');
	popUpHeader.className = 'header';
	popUpHeader.innerHTML = getMenuItemsInLang(messageTypeKeyWords[indexOfMessageType]);
	
	var popUpContentDiv = document.createElement('div');
	popUpContentDiv.className = 'content';
	
	var customMessageSubjectTable = document.createElement('table');
	customMessageSubjectTable.className = 'table01';
	customMessageSubjectTable.setAttribute('cellpadding', '0');
	customMessageSubjectTable.setAttribute('cellspacing', '0');
	customMessageSubjectTable.style.width = '100%';
	customMessageSubjectTable.style.margin = '5';
	
	var customMessageSubjectTableBody = document.createElement('tbody');
	
	var customMessageSubjectTableHeader = document.createElement('th');
	customMessageSubjectTableHeader.setAttribute('colspan', '3');	
	customMessageSubjectTableBody.appendChild( customMessageSubjectTableHeader );
	
	var actualRow = document.createElement('tr');
	
	var actualCell = document.createElement('td');
	var customMessageSubjectInput = createInputElement('text', 'custom_message_subject_ID', null, 'textfield' );
	customMessageSubjectInput.size = 15;
	actualCell.appendChild( customMessageSubjectInput ) ;
	
	actualRow.appendChild( actualCell );
	
	addButtonCell = createButtonLikeCell('>>') ;
	addButtonCell.style.margin = '5';
	addEvent( addButtonCell, 'click', function(objId){showHideObject(popUp.id);}, true );
	
	addEvent( addButtonCell, 'click', function(objId){searchAndReplacePreviousSubject(getKeywordsInLang(messageTypeKeyWords[indexOfMessageType]), document.getElementById('custom_message_subject_ID').value )}, true );
	actualRow.appendChild( addButtonCell );
	
	cancelButtonCell = createButtonLikeCell('X') ;
	cancelButtonCell.style.margin = '5';
	addEvent( cancelButtonCell, 'click', function(objId){showHideObject(popUp.id);}, true );
	actualRow.appendChild( cancelButtonCell );
	
	customMessageSubjectTableBody.appendChild( actualRow );	
	
	customMessageSubjectTable.appendChild( customMessageSubjectTableBody );
	
	popUpContentDiv.appendChild( customMessageSubjectTable );
	
	popUp.appendChild( popUpHeader );
	popUp.appendChild( popUpContentDiv );	
	
	var footerDiv = document.createElement('div');
	footerDiv.className = 'footer';
	popUp.appendChild( footerDiv );
	
	return popUp;
	
}

function createPopUpDivForTradeMessages( indexOfMessageType )	{
	var popUp = document.createElement('div');
	popUp.id = messageTypeKeyWords[indexOfMessageType] + '_popUpDiv';
	
	// TODO : Somehow resize the imported background image in width and avoid thickening the vertical sidelines
	var plannedWidth = 70;
	if (  messageTypeKeyWords[indexOfMessageType] == 'CHANGE' )	{
		plannedWidth = 150;
	}	
	
	popUp.className = 'dynamic';
	popUp.style.position = 'absolute'; 
	popUp.style.left = '40px';
	popUp.style.zIndex = '3';
//	popUp.style.width = plannedWidth + 'px'; 
	popUp.style.visibility = 'hidden'; 
	
	var popUpHeader = document.createElement('h3');
	popUpHeader.className = 'header';
	popUpHeader.innerHTML = getMenuItemsInLang(messageTypeKeyWords[indexOfMessageType]);
//	popUpHeader.style.width = plannedWidth + 'px'; 

	var popUpContentDiv = document.createElement('div');
	popUpContentDiv.className = 'content';
//	popUpContentDiv.style.width = plannedWidth + 'px'; 

	var tableForDisplay = document.createElement('table');
	tableForDisplay.className = 'table01';
	tableForDisplay.setAttribute('cellpadding', '0');
	tableForDisplay.setAttribute('cellspacing', '0');
	tableForDisplay.style.width = '100%';
	
	var tableForDisplayBody = document.createElement('tbody');
	
	var actualRow = document.createElement('tr');
	actualRow.style.border.bottom = '1px dotted yellow';	
	
	if ( messageTypeKeyWords[indexOfMessageType] == 'CHANGE' )	{

		for ( x in resourceTypeKeyWords )	{			
			for ( y in resourceTypeKeyWords ) {
				if ( x == y ) {
					continue;		// Useless to say: exchange wood for wood ...
				}
				actualRow = document.createElement('tr');
				actualRow.id = messageTypeKeyWords[indexOfMessageType] + '_' + getResourceNamesInLang(resourceTypeKeyWords[x]) + '_' + getResourceNamesInLang(resourceTypeKeyWords[y]);
				actualRow.style.border.bottom = '1px dotted yellow';				
				// '#FDF7DD' = creamwhite
				// '#ECD5AC' = creamypinky
				addEvent( actualRow, 'mouseover', function(){ this.bgColor='#ECD5AC'; }, true );				
				addEvent( actualRow, 'mouseout', function(){ this.bgColor=null; }, true );
				addEvent( actualRow, 'click', function(){ appendResourceMarkersToMessage(this.id); }, false );	
			
				actualCol = document.createElement('td');				
				actualCol.appendChild ( createSubjectPicture( resourceNamesForAdditionalParams[getResourceNamesInLang(resourceTypeKeyWords[x])] ) );
				actualRow.appendChild ( actualCol );
				
				actualCol = document.createElement('td');				
				actualCol.appendChild( createSubjectPicture( EXCHANGE_DIRECTION_ICON_PATH ) );
				actualRow.appendChild ( actualCol );		
				
				actualCol = document.createElement('td');				
				actualCol.appendChild ( createSubjectPicture( resourceNamesForAdditionalParams[getResourceNamesInLang(resourceTypeKeyWords[y])]  ) );
				actualRow.appendChild ( actualCol );				
				
				tableForDisplayBody.appendChild ( actualRow );				
			}			
		}
	}
	else	{
		for ( x in resourceTypeKeyWords )	{

			actualRow = document.createElement('tr');
			actualRow.id = messageTypeKeyWords[indexOfMessageType] + '_' + getResourceNamesInLang(resourceTypeKeyWords[x]);
			actualRow.style.border.bottom = '1px dotted yellow';
			addEvent( actualRow, 'mouseover', function(){ this.bgColor='#ECD5AC'; }, true );				
			addEvent( actualRow, 'mouseout', function(){ this.bgColor=null; }, true );
			addEvent( actualRow, 'click', function(){ appendResourceMarkersToMessage(this.id); }, false );	
		
			actualCol = document.createElement('td');
			actualCol.appendChild ( createSubjectPicture( resourceNamesForAdditionalParams[getResourceNamesInLang(resourceTypeKeyWords[x])] ) );
			actualRow.appendChild ( actualCol );		
							
			tableForDisplayBody.appendChild ( actualRow );
			
		}
	}

	tableForDisplay.appendChild( tableForDisplayBody ) ;
	popUpContentDiv.appendChild( tableForDisplay );
	
	
	popUp.appendChild( popUpHeader );
	popUp.appendChild( popUpContentDiv );
	
	var footerDiv = document.createElement('div');
	footerDiv.className = 'footer';
//	footerDiv.style.width = plannedWidth + 'px'; 
	popUp.appendChild( footerDiv );
	
	return popUp;
}

/*

Functions to manipulate message marker during the sender stream

*/

function insertMessageSubject( subjectType, originalMessageText )	{	
	messageText = messageMarkerSeparator + subjectType + messageMarkerSeparator + originalMessageText ;
	var originalMessageTextArea = $X(".//*[@id='mainview']/div/form/span/textarea[@id='text']");
	originalMessageTextArea.value = messageText;
}

function searchAndReplacePreviousSubject(subjectType, customText)	{	
	var newSubjectType = ( 'undefined' == customText || null == customText ) ? subjectType : subjectType + ' ' + customText;	
	var originalMessageTextArea = $X(".//*[@id='mainview']/div/form/span/textarea[@id='text']");
	var originalMessageText = originalMessageTextArea.value	
	startAndEndPosOfMessageMarker = searchForMessageMarker(messageMarkerSeparator , originalMessageText);	
	if ( startAndEndPosOfMessageMarker[0] < 0 )	{		// No special separators -> no special subject in the message
		insertMessageSubject(newSubjectType, originalMessageText);
		return;
	}		
	if ( startAndEndPosOfMessageMarker[0] != -1 && startAndEndPosOfMessageMarker[1] != -1  )	{	
		originalMessageText = deleteMarkerFromMessage( startAndEndPosOfMessageMarker, originalMessageText );
		insertMessageSubject(newSubjectType, originalMessageText);
	}
	
}

function searchForMessageMarker(messageMarkerSeparator, messageText)	{
	var res = new Array(2);
	res[0] = -1;
	res[1] = -1;
	// No marker in message
	res[0] = messageText.indexOf(messageMarkerSeparator);
	if ( res[0] != -1 )	{	
		res[1] = messageText.indexOf(messageMarkerSeparator, res[0] + 1) + messageMarkerSeparator.length ;
	}
	return res;
}

function deleteMarkerFromMessage( startAndEndPosOfMessageMarker, messageText )	{	
	if ( 'undefined' == startAndEndPosOfMessageMarker|| null == startAndEndPosOfMessageMarker) {
		startAndEndPosOfMessageMarker = searchForMessageMarker(messageMarkerSeparator, messageText);
	}	
	return messageText.substring (0, startAndEndPosOfMessageMarker[0] ) + messageText.substring (  startAndEndPosOfMessageMarker[1] );
}

function appendResourceMarkersToMessage( elementId )	{			
	var subjectType = elementId.replace(/_/g, ' ');
	var splittedSubject = subjectType.split( ' ' );
	var subjectTypeRegex = new RegExp(splittedSubject[0]);
	searchAndReplacePreviousSubject( subjectType.replace( subjectTypeRegex,  getKeywordsInLang( splittedSubject[0] ) ) , null );
}

function replaceBackLinkStartValue()	{
	if ( pagesToLoad == 1 )	{
		return;
	}
	
	var messageCountPerPages = userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'];
	var backToPreviousPageLink = $X(".//*[@id='container']/div[@id='container2']/div[@id='backTo']/div[@class='content']/a");	
	var linkText = backToPreviousPageLink.href;
	var startText = linkText.substring( linkText.search(/start=/) );
	var indexValue =  parseInt(startText.substring( startText.search(/=/) + 1 ) );
	
	var newIndexValue = Math.floor( indexValue / messageCountPerPages ) * messageCountPerPages ;
	var newLinkText = linkText.substring(0, linkText.search(/start=/) ) + 'start=' + newIndexValue;
	
	backToPreviousPageLink.href = newLinkText;	
}